<template>
	<view class="topHeader">
		<MyHeader background="linear-gradient(to bottom, #00aaff, #ffffff)" :title="userName"></MyHeader>
	</view>
	<scroll-view class="messageScrollView" scroll-y :scroll-into-view="scrollToView" :scroll-with-animation="true"
		@scrolltoupper="handleScrollToTop" @scrolltolower="handleScrollToBottom">
		<view :style="{paddingTop:navInfo.height + navInfo.top * 2+'px'}" ref="messageContent" class="messageContent">
			<view class="msgBox" v-for="(item,index) in messages" :key="item.id" :id="'msg-' + index"
				:ref="`msg-${index}`">

				<view class="leftBox" v-if='item.senderId!=id'>
					<img class="leftImg" :src="receiveImg" alt="" />
					<view class="leftMsg">
						{{item.message}}
					</view>
				</view>
				<view class="rightBox" v-if='item.senderId==id'>
					<view class="rightMsg">
						{{item.message}}
					</view>
					<img class="rightImg" :src="userStore.userInfo.imageUrl" alt="" />
				</view>
			</view>
		</view>
	</scroll-view>
	<up-tabbar class="tabbar" :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
		<view class="inputBox">
			<up-input class="sendinput" shape='circle' placeholder="请输入内容" border="surround"
				v-model="inputMessage"></up-input>
			<up-button class="sendbtn" type="primary" text="确定" @click="sendMessage"></up-button>
		</view>
	</up-tabbar>

</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted,
		onUnmounted,
		nextTick,
		computed
	} from 'vue';
	import Setting from '@/setting.js'
	import {
		useUserStore
	} from '@/store/useUserStore.js';
	import {
		gethistoryListAPI
	} from '@/apis/partTime.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	const userStore = useUserStore()
	const id = ref('')
	id.value = userStore.userInfo.id


	const ws = ref(null);
	const inputMessage = ref('');
	const messages = ref([]);
	const navInfo = reactive(wx.getMenuButtonBoundingClientRect())
	const connectWebSocket = () => {
		const settingUrl = Setting.websocketUrl.substring(7)
		const url = `ws://${settingUrl}/chat/${id.value}`;
		ws.value = uni.connectSocket({
			url: url,
			header: {
				'content-type': 'application/json'
			},
			success: () => {
				console.log('WebSocket连接成功');
			},
			complete: (res) => {
				// console.log(11, res);
			}
		});
		ws.value.onOpen(() => {})
		ws.value.onMessage((message) => {
			const receiveMsg = JSON.parse(message.data)
			console.log(receiveMsg);
			const newMessage = {
				receiverId: id.value,
				senderId: receiverId.value,
				message: receiveMsg.message,
				sentTime: getCurrentFormattedTime(),
				module: module.value,
			}

			messages.value.push(newMessage);
			scrollToBottom();
		});

		ws.value.onClose(() => {
			console.log('WebSocket连接已关闭');
		});

		ws.value.onError((error) => {
			console.log('WebSocket连接出错:', error.errMsg);
		});
	}


	const getCurrentFormattedTime = () => {
		// 创建一个新的Date对象，获取当前时间
		const now = new Date();

		// 获取年、月、日、时、分、秒
		const year = now.getFullYear(); // 年份
		const month = now.getMonth() + 1; // 月份（从0开始计数）
		const day = now.getDate(); // 日
		const hour = now.getHours(); // 小时
		const minute = now.getMinutes(); // 分钟
		const second = now.getSeconds(); // 秒

		// 格式化时间，确保每个部分都是两位数
		const formattedYear = year.toString();
		const formattedMonth = month.toString().padStart(2, '0');
		const formattedDay = day.toString().padStart(2, '0');
		const formattedHour = hour.toString().padStart(2, '0');
		const formattedMinute = minute.toString().padStart(2, '0');
		const formattedSecond = second.toString().padStart(2, '0');

		// 组合成最终的格式化字符串
		const formattedTime =
			`${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;

		return formattedTime;
	}
	getCurrentFormattedTime()
	const sendMessage = () => {
		if (inputMessage.value.trim() === '') return;
		const message = {
			receiverId: receiverId.value,
			senderId: id.value,
			message: inputMessage.value,
			sentTime: getCurrentFormattedTime(),
			module: module.value,
		};
		messages.value.push(message);
		if (ws.value.readyState == 1) {
			const jsonSenfMsg = JSON.stringify(message)
			uni.sendSocketMessage({
				data: jsonSenfMsg
			});

			inputMessage.value = '';
			scrollToBottom();
		}
	};
	const getHistortList = async (targetUserId, module) => {
		const res = await gethistoryListAPI({
			senderId: id.value,
			receiverId: targetUserId,
			module
		})
		messages.value = res.data
		// 滚动到底部
		nextTick(() => {
			scrollToBottom();
		});
	}
	const receiverId = ref('')
	const senderId = ref('')
	const module = ref('')
	const receiveImg = ref('')
	const userName = ref('')

	const scrollToView = ref('');
	const isAutoscroll = ref(true);
	const messageContent = ref(null);

	const scrollToBottom = async () => {
		if (!isAutoscroll.value) return;
		// 如果没有消息，不执行滚动
		if (messages.value.length === 0) return;
		// 设置滚动到的节点 ID
		scrollToView.value = `msg-${messages.value.length - 1}`;
	};

	onLoad((options) => {
		getHistortList(options.targetUserId, options.module)
		receiverId.value = options.targetUserId
		module.value = options.module
		receiveImg.value = options.receiveImg
		userName.value = options.userName
	})
	onMounted(() => {
		connectWebSocket();
	});

	onUnmounted(() => {
		if (ws.value) {
			ws.value.close();
		}
	});

	const bottomsafeAreaInsets = ref('')

	uni.getSystemInfo({
		success: (res) => {
			bottomsafeAreaInsets.value = res.safeAreaInsets.bottom
		},
		fail: (err) => {
			console.error('获取设备信息失败：', err);
		}
	})
</script>

<style scoped lang="scss">
	.messageScrollView {
		height: 90vh;
		/* 或具体高度 */
		overflow-y: scroll;
		z-index: 99;
	}

	.topHeader {
		position: fixed;
		top: 0;
		left: 0;
		width: 750rpx;
		z-index: 9999;
	}

	.messageContent {
		// padding-bottom: 100rpx;
	}

	.inputBox {
		background-color: #fff;
		display: flex;
		padding: 10rpx 20rpx;
		width: 750rpx;

		.sendbtn {
			width: 100rpx;
			margin-left: 20rpx;
		}
	}

	.msgBox {
		padding: 12rpx;

		.leftBox {
			display: flex;
			margin-bottom: 28rpx;

			.leftImg {
				width: 64rpx;
				height: 64rpx;
				border-radius: 12rpx;
				margin-right: 16rpx;
			}

			.leftMsg {
				background-color: #fff;
				max-width: 472rpx;
				border-radius: 8rpx;
				padding: 10rpx;
			}
		}

		.rightBox {
			display: flex;
			justify-content: flex-end;
			margin-bottom: 28rpx;


			.rightImg {
				width: 64rpx;
				height: 64rpx;
				border-radius: 12rpx;
				margin-left: 16rpx;
			}

			.rightMsg {
				max-width: 472rpx;
				border-radius: 8rpx;
				background: rgba(229, 241, 255, 1);
				padding: 10rpx;
			}
		}
	}
</style>